package controllers

import (
	"blog/models"
	"blog/syserror"
	"errors"
	"github.com/astaxie/beego"
	"github.com/satori/go.uuid"
)

const SessionUserKey = "SESSION_USER_KEY"

type BaseController struct {
	beego.Controller
	User    models.User
	IsLogin bool
}

type NestPreparer interface {
	NextPrepare()
}

func (this *BaseController) Prepare() {
	this.Data["Path"] = this.Ctx.Request.RequestURI
	u, ok := this.GetSession(SessionUserKey).(models.User)
	this.IsLogin = false
	if ok {
		this.User = u
		this.IsLogin = true
		this.Data["User"] = this.User
	}
	this.Data["isLogin"] = this.IsLogin

	if a, ok := this.AppController.(NestPreparer); ok {
		a.NextPrepare()
	}
}

func (this *BaseController) Abort500(err error) {
	this.Data["error"] = err
	this.Abort("500")
}

//字符串不能为空公共方法
func (this *BaseController) GetMustString(key, msg string) string {
	ustring := this.GetString(key)
	if len(ustring) == 0 {
		this.Abort500(errors.New(msg))
	}
	return ustring
}

//退出必须先登录
func (this *BaseController) MustLogin() {
	if !this.IsLogin {
		this.Abort500(syserror.UnLoginUser{})
	}
}

//不带返回数据，错误返回
func (this *BaseController) JsonReturn(code int, msg, action string) {
	this.Data["json"] = H{
		"code":   code,
		"action": action,
		"msg":    msg,
	}
	this.ServeJSON()
}

type H map[string]interface{}

//带返回数据
func (this *BaseController) JsonH(code int, msg string, data H) {
	data["code"] = code
	data["msg"] = msg
	this.Data["json"] = data
	this.ServeJSON()
}

//生成唯一id串
func (this *BaseController) UUID() string {
	u, err := uuid.NewV4()
	if err != nil {
		this.Abort500(syserror.New(300, "系统错误", err))
	}
	return u.String()
}
